<template>
  <!-- 充值余额的弹框组件 -->
  <Dialog
    :title="dialogConfig.title"
    :buttons="dialogConfig.buttons"
    :show="dialogConfig.show"
    @close="dialogConfig.show = false"
    :width="'700px'"
  >
    <el-form
      ref="formDataRef"
      :model="formData"
      :rules="rules"
      label-width="60px"
    >
      <el-form-item label="当前余额:" label-width="90px">
        {{ balance / 100 }} 元
      </el-form-item>
      <el-form-item label="充值金额:" prop="rechargeBalance" label-width="90px">
        <el-input
          :maxLength="10"
          v-model.trim="formData.rechargeBalance"
          placeholder="请输入充值金额"
        />
      </el-form-item>
      <el-form-item label="密码:" prop="password" label-width="90px">
        <el-input
          type="password"
          :maxLength="100"
          v-model.trim="formData.password"
          placeholder="请输入密码"
        />
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();

const balance = ref(0);

const dialogConfig = reactive({
  show: false,
  title: "充值余额",
  buttons: [
    {
      type: "primary",
      text: "确认",
      click: (e) => {
        submitData();
      },
    },
  ],
});

const formData = ref({});
const formDataRef = ref();
const rules = {
  rechargeBalance: [
    { required: true, message: "请输入充值金额", trigger: "blur" },
  ],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
};

import md5 from "js-md5";

const emit = defineEmits(["reload"]);
const submitData = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let params = {};
    Object.assign(params, formData.value);
    params.password = md5(params.password);
    params.rechargeBalance = params.rechargeBalance * 100; // 转为元
    let result = await proxy.Request({
      method: "put",
      url: proxy.Api.updateInfo,
      params,
    });
    if (!result) {
      return;
    }
    proxy.Message.success("充值成功");
    dialogConfig.show = false;
    emit("reload");
  });
  dialogConfig.show = false;
};

const show = async () => {
  // 获取余额
  let result = await proxy.Request({
    url: proxy.Api.getUserInfo,
  });
  if (!result) {
    return;
  }
  balance.value = result.data.balance;
  dialogConfig.show = true;
};
defineExpose({
  show,
});
</script>

<style lang="scss" scoped></style>
